package base.stream.normal;

import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;

public class StringDemo {
    public static void main(String[] args) {

        /*
         * 三参数的collect方法
         */
        String s = Stream.of("this", "is", "a", "list")
                .collect(() -> new StringBuilder(), (sb, str) -> sb.append(str), (sb1, sb2) -> sb1.append(sb2)).toString();

        /*
         * 三参数的collect方法-方法引用
         */
        String s2 = Stream.of("this", "is", "a", "list")
                .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();

        /*
         * Collectors.joining(),joining 方法的重载形式传入字符串定界符，其简单易行无出其右
         */
        String s3 = Stream.of("this", "is", "a", "list").collect(Collectors.joining());


        /*
         * 根据长度对字符串排序
         */
        Stream<String> stringStream = Stream.of("this", "is", "a", "list", "of", "string");
        List<String> stringList = stringStream.sorted(Comparator.comparingInt(String::length))
                .collect(Collectors.toList());

        stringList.stream().reduce((prev, curr) -> {
            System.out.println("prev: " + prev + ", curr: " + curr);
            assertTrue(prev.length() <= curr.length());
            return curr;
        });

        /**
         * 回文检测
         * */
        assertTrue(Stream.of("Madam, in Eden, I'm Adam",
                        "Go hang a salami; I'm a lasagna hog",
                        "Flee to me, remote elf!",
                        "A Santa pets rats as Pat taps a star step at NASA")
                        .allMatch(StringDemo::isPalindrome));
        assertFalse(isPalindrome("This is NOT a palindrome"));


    }

    /**
     * Java7的回文检测
     */
    public static boolean isPalindrome(String s) {
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (Character.isLetterOrDigit(c)) {
                sb.append(c);
            }
        }
        String forward = sb.toString().toLowerCase(Locale.ROOT);
        String backward = sb.reverse().toString().toLowerCase(Locale.ROOT);
        return forward.equals(backward);
    }

    /**
     * Java8的回文检测-codePoints()
     */
    public static boolean isPalindromeInJava8(String s) {
        String forward = s.toLowerCase(Locale.ROOT).codePoints()
                .filter(Character::isLetterOrDigit)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                .toString();

        String backward = new StringBuilder(forward).reverse().toString();
        return forward.equals(backward);
    }
}
